﻿package src.states{
	import src.CountDown;
	import src.Const;
	import src.game.managers.SoundManager;
	import src.sound.SoundPlayer;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.Event;

	public class NewLevel extends GameState {
		
		private var newLevelMovie:NewLevelMovie;
		private var countDown:MovieClip;
		private var levelNumber:int = 0;
		
		public function NewLevel(display:DisplayObjectContainer, gameStates:GameStatesMachine) {
			super(display, gameStates);
		}
		
		public override function init():void {
			super.init();
			levelNumber++;
			if (areMoreLevels()) {
				initNewLevelMovieClip();
				initCountDown();
			}
			else 
				gameStates.setCurrentState(gameStates.getEndGameState());
			
		}
		
		private function areMoreLevels():Boolean {
			return (levelNumber <= Const.MAX_LEVELS) ? true : false;
		}
		
		private function initNewLevelMovieClip():void {
			newLevelMovie = new NewLevelMovie();
			trace(newLevelMovie.level.text);
			newLevelMovie.level.selectable = false;
			newLevelMovie.level.embedFonts = true;
			//newLevelMovie.level.border = true;
			newLevelMovie.level.text = "Poziom " + levelNumber;
			newLevelMovie.x = 0;
			newLevelMovie.y = displayContent.height/4;
			displayContent.addChild(newLevelMovie);
		}
		
		private function initCountDown():void {
			countDown = new CountDown();
			countDown.x = newLevelMovie.width/2;
			countDown.y = displayContent.stage.stageHeight - displayContent.stage.stageHeight / 5;
			countDown.addEventListener(Event.CHANGE, playSound);
			countDown.play();
			displayContent.addChild(countDown);
		}
		
		private function playSound(event:Event):void {
			var sm:SoundManager = SoundManager.getInstance();
			sm.add(new SoundPlayer(new CountdownClick()));
		}
		
		public override function update():void {
			if ( areMoreLevels() ) {
				if (countDown.currentFrame == countDown.totalFrames) {
					countDown.stop();
					gameStates.setCurrentState(gameStates.getGameplayState());
				}
			}
			else {
				trace ("end game");
				gameStates.setCurrentState(gameStates.getEndGameState());
			}
		}
		
		public override function restart():void {
			levelNumber = 0;
		}
		
		public override function dispose():void {
			super.dispose();
			if (newLevelMovie != null)
				displayContent.removeChild(newLevelMovie);
			if (countDown != null)
				displayContent.removeChild(countDown);
			newLevelMovie = null;
			if (countDown != null)
				countDown.removeEventListener(Event.CHANGE, playSound);
			countDown = null;
		}
	}
}
